package com.dadaguai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dadaguai.common.BusinessException;
import com.dadaguai.common.R;
import com.dadaguai.constants.ResponseCode;
import com.dadaguai.constants.UserConstants;
import com.dadaguai.domain.ForumArticle;
import com.dadaguai.domain.LikeRecord;
import com.dadaguai.dto.ForumArticleDto;
import com.dadaguai.dto.UserInfoDto;
import com.dadaguai.mapper.LikeRecordMapper;
import com.dadaguai.service.ForumArticleService;
import com.dadaguai.mapper.ForumArticleMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王半仙
 * @description 针对表【forum_article(文章信息)】的数据库操作Service实现
 * @createDate 2023-10-20 11:28:40
 */
@Service
public class ForumArticleServiceImpl extends ServiceImpl<ForumArticleMapper, ForumArticle>
        implements ForumArticleService {

    @Autowired
    ForumArticleMapper forumArticleMapper;

    @Autowired
    LikeRecordMapper likeRecordMapper;

    /**
     * 分页获取板块下的所有文章
     *
     * @param session
     * @param boardId     板块id
     * @param sort        排序方式（降序）0=默认  1=阅读量，2=发布时间，3=点赞量
     * @param page        当前页
     * @param size
     * @param searchField
     * @return
     */
    @Override
    public R getArticleList(HttpSession session, String boardId, String sort, Integer page, Integer size, String searchField) {
        //拼接模糊查询条件
        String str = null;
        if (StringUtils.isNoneEmpty(searchField)) {
            str = "%" + searchField + "%";
        }
        List<ForumArticle> articleList = forumArticleMapper.getArticle(boardId, sort, (page - 1) * size, size, str);
        Integer total = forumArticleMapper.selectCountByBoardId(boardId,searchField);
        List<ForumArticleDto> articleDtoList = articleList.stream().map(article -> {
            ForumArticleDto articleDto = new ForumArticleDto();
            BeanUtils.copyProperties(article, articleDto);
            //判断用户是否登录
            String userId = (String) session.getAttribute(UserConstants.USER_ID_KEY);
            //查询数据库，判断用户是否给该帖子点赞
            if (StringUtils.isNoneEmpty(userId)) {
                Integer count = likeRecordMapper.selectGoodCount(article.getArticleId(), userId);
                if (count == 0) {
                    //未点赞
                    articleDto.setIsLiked(0);
                } else {
                    //已点赞
                    articleDto.setIsLiked(1);
                }
            }
            // 高亮显示搜索关键字
            if (StringUtils.isNoneEmpty(searchField)) {
                article.setSummary(article.getSummary().replace(searchField, "<span <span style=\"color: red;\">" + searchField + "</span>"));
            }
            return articleDto;
        }).collect(Collectors.toList());

        return R.success(articleDtoList).add("total", total);
    }

    /**
     * 获取帖子详情，并检查当前用户是否对该帖子点赞
     *
     * @param id       帖子id
     * @param userInfo
     * @return
     * @throws BusinessException
     */
    @Transactional
    @Override
    public ForumArticleDto getArticleInfo(String id, UserInfoDto userInfo) throws BusinessException {

        ForumArticle article = forumArticleMapper.selectById(id);
        if (article == null) {
            throw new BusinessException("数据查询异常", ResponseCode.DATA_QUERY_ERROR);
        }
        //对象拷贝
        ForumArticleDto articleDto = new ForumArticleDto();
        BeanUtils.copyProperties(article, articleDto);
        //增加帖子阅读量
        forumArticleMapper.updateReadCount(id);

        //用户未登录
        if (userInfo == null) {
            articleDto.setIsLiked(0);
        }
        //判断当前帖子是否点赞
        if (userInfo != null) {
            Integer count = likeRecordMapper.selectGoodCount(id, userInfo.getUserId());
            if (count == 0) {
                //未点赞
                articleDto.setIsLiked(0);
            } else {
                //已点赞
                articleDto.setIsLiked(1);
            }
        }
        return articleDto;
    }

    /**
     * 更新点赞、评论记录
     *
     * @param articleId 帖子id
     * @param type      1=点赞 ；2=评论 ；3=收藏 ； 4=分享
     * @param userId
     */
    @Transactional
    @Override
    public void updateArticleCount(String articleId, Integer type, String userId) {
        ForumArticle article = forumArticleMapper.selectById(articleId);

        //点赞
        if (type == 1) {
            // 判断用户是否点赞
            Integer count = likeRecordMapper.selectGoodCount(articleId, userId);
            if (count == 0) {
                article.setGoodCount(article.getGoodCount() + 1);
                //获取帖子作者id
                String authorId = forumArticleMapper.selectAuthorId(articleId);
                //新增点赞记录
                LikeRecord likeRecord = new LikeRecord();
                likeRecord.setObjectId(articleId);
                likeRecord.setUserId(userId);
                likeRecord.setCreateTime(new Date());
                likeRecord.setOpType(0);
                likeRecord.setAuthorUserId(authorId);
                likeRecordMapper.insert(likeRecord);

                //增加帖子点赞数
                forumArticleMapper.addGoodCount(articleId);
                // TODO: 2023/11/1 通知帖子作者，有新的点赞
            } else {
                article.setGoodCount(article.getGoodCount() - 1);
                //删除点赞记录
                likeRecordMapper.deleteGoodCount(articleId, userId);
                //减少帖子点赞数
                forumArticleMapper.minusGoodCount(articleId);
            }

        }

    }
}




